<template>
  <div class="container">
    <div class="goods-content bg-color-white pad-l-15 pad-r-15">
      <div class="pad-t-12 pad-b-12 font-13">退款商品</div>
      <div v-for="(skuList, index) in goodsList" :key="index">
        <div v-if="index < 1">
          <div class="flex pad-r-8">
            <div class="width-79 height-79 img-box"><img v-if="skuList[0].goodsImageUrl" :src="skuList[0].goodsImageUrl" alt="" class="width-79 height-79"></div>
            <div class="line-2 flex-item mar-l-10">{{skuList[0].goodsTitle}}</div>
          </div>
          <div>
            <template v-for="(sku, skuIndex) in skuList">
              <div :key="skuIndex" class="sku-block" v-if="skuIndex < 2">
                <div class="flex flex-between height-52 pad-l-10 pad-r-15 sku-row">
                  <div class="font-12 font-color-6">
                    <div class="flex sku-detail" v-if="sku.skuDetail">
                      <div>规格：</div>
                      <div class="width-200 line-1">{{sku.skuDetail}}</div>
                    </div>
                    <div>￥{{sku.goodsPrice}}<span v-if="sku.unit">/{{sku.unit}}</span></div>
                  </div>
                  <div class="font-15">×{{sku.goodsNum}}</div>
                </div>
              </div>
            </template>
          </div>
          <div class="flex flex-center pad-t-18 pad-b-14 line-h-1 font-11 font-color-6">
            <div @click="$pt.navigateTo({url: '/pages/personal/order/detail/main?orderId=' + orderId})">查看更多</div>
            <van-icon name="arrow" size="13px" />
          </div>
        </div>
      </div>
    </div>
    <div class="bg-color-white line-h-1 mar-t-10">
      <div class="flex flex-between font-13 pad-l-15 pad-r-15 pad-t-15 pad-b-15">
        <div>
          <span>退款金额(含运费):</span>
        </div>
        <div class="color-red"><span>￥</span><span>{{order.actualPrice}}</span></div>
      </div>
      <div class="flex flex-between font-13 pad-l-15 pad-r-15 pad-t-10 pad-b-18">
        <div>
          <span class="color-red">*</span>
          <span>退款原因:</span>
        </div>
        <div class="font-12 font-color-9" @click="showSelect = true">
          <div v-if="refundReason">{{refundReason}}</div>
          <div v-else class="flex flex-center">
            <span>请选择</span>
            <van-icon name="arrow" size="13px" color="#999" />
          </div>
        </div>
      </div>
    </div>
    <div class="mar-t-10 reason-cell">
      <van-cell-group :border='false'>
        <van-field
          :value="mark"
          clearable
          label="退款说明:"
          placeholder="选填"
          title-width="70px"
          @change="onMarkChange"
        />
      </van-cell-group>
    </div>
    <div class="pad-l-15 pad-r-15 pad-b-13 mar-t-10 bg-color-white">
      <div class="pad-t-10 pad-b-10">退款凭证<span class="font-13 font-color-9 mar-l-10">(选填)</span></div>
      <upload-img @upLoadSuccess="upLoadSuccess" @upLoadFail="upLoadFail" @uploadDelete="uploadDelete" :showTip='false'
        :maxLength=3 :count=3></upload-img>
    </div>
    <div class="pad-t-25 pad-b-25 text-align-c">
      <button class="submit-btn" @click="cancelOrder">提交</button>
    </div>
    <van-popup
      :show="showSelect"
      round
      position="bottom"
      @close="onClose"
    >
      <van-picker :columns="columns" @change="onChange" @confirm="onConfirm" @cancel="onCancel" show-toolbar />
    </van-popup>
  </div>
</template>
<script>
import UploadImg from '@/components/UploadImg1'
import { doCancelPaidOrder, listAfterSaleReason } from '@/api/personal'
import { getProjectOrder } from '@/api/distribution'
export default {
  components: { UploadImg },
  data() {
    return {
      mark: '',
      memberId: '',
      orderId: '',
      order: {},
      goodsList: [],
      columns: [],
      showSelect: false,
      afterSaleReasonId: '',
      refundReason: '',
      timer: null,
      isUploadFinish: false,
      files: [],
      imgFiles: []
    }
  },
  // 监听上传是否完成
  watch: {
    isUploadFinish(val) {
      if (this.isUploadFinish) {
        this.doSave()
      }
    }
  },
  onLoad() {
    // 初始化data
    Object.assign(this.$data, this.$options.data())
  },
  onShow() {
    this.memberId = this.getCurrentPage().query.memberId
    this.orderId = this.getCurrentPage().query.orderId
    this.getOrder()
    this.listAfterSaleReason()
  },
  onUnload() {
    clearTimeout(this.timer)
    this.timer = null
  },
  methods: {
    getOrder() {
      this.$pt.showLoading()
      getProjectOrder(this.orderId).then(response => {
        this.$pt.hideLoading()
        if (response.isError) return
        this.order = response.data
        const goodsMap = {}
        this.order.orderGoodsList.forEach(orderGoods => {
          let skuList = goodsMap[orderGoods.goodsId]
          if (!skuList) {
            skuList = []
          }
          skuList.push(orderGoods)
          goodsMap[orderGoods.goodsId] = skuList
        })
        this.goodsList = []
        for (let key in goodsMap) {
          this.goodsList.push(goodsMap[key])
        }
        // console.log(this.goodsList)
      })
    },
    listAfterSaleReason() {
      let params = {
        enterpriseId: this.getEnterpriseId,
        cancelOrderFlag: 1
      }
      this.columns = []
      listAfterSaleReason(params).then(response => {
        if (response.isError) return
        response.data.forEach(item => {
          if (item.delFlag === 0) {
            this.columns.push({
              text: item.cancelReason,
              reasonId: item.reasonId
            })
          }
        })
      })
    },
    onMarkChange(e) {
      // 退款说明输入框
      this.mark = e.mp.detail
    },
    onClose() {
      // 关闭底部弹窗
    },
    onChange(e) {
      // 选择器变动
    },
    onCancel(e) {
      // 取消选择
      this.showSelect = false
    },
    onConfirm(e) {
      // 确认选择 取消订单原因
      this.refundReason = e.mp.detail.value.text
      this.afterSaleReasonId = e.mp.detail.value.reasonId
      this.showSelect = false
    },
    upLoadSuccess(res) {
      console.log(res)
      this.files = res.files
    },
    upLoadFail(res) {
      // console.log(res)
    },
    upLoadComplete() {
      console.log('complete')
    },
    uploadDelete(res) {
      // console.log(res)
    },
    doSave() {
      if (!this.isUploadFinish) {
        // if (this.files.length === 0) return this.$utils.showToast({ title: '请选择要上传的照片' })
        if (this.files.length > 0) {
          this.$utils.showToast({
            title: '图片上传中',
            icon: 'loading',
            duration: 150000,
            mask: true
          })
          // 开始上传文件
          this.doUpload()
        } else {
          this.doCancelPaidOrder()
        }
      } else {
        // 上传完成，清除数据
        this.files = []
        this.doCancelPaidOrder()
      }
    },
    doUpload() {
      const that = this
      let finishCount = 0
      this.files.forEach(file => {
        // 使用微信上传（只能单张上传）
        const uploadTask = that.$pt.uploadFile({
          url: process.env.BASE_API + '/common/uploadFiles',
          filePath: file,
          name: 'files',
          success(res) {
            const result = JSON.parse(res.data)
            if (result.code === 101) {
              console.log('我图片上传啦', result.data)
              that.imgFiles.push(result.data[0])
            } else {
              that.$utils.showToast({ title: '图片上传发生错误:' + result.msg })
              finishCount--
            }
          },
          complete() {
            finishCount++
            if (that.files.length === finishCount) {
              that.isUploadFinish = true
            }
          }
        })
        uploadTask.onProgressUpdate((res) => {
          console.log('上传进度', res.progress)
        })
      })
    },
    doCancelPaidOrder() {
      console.log(this.order)
      let goodsList = []
      this.order.orderGoodsList.forEach(item => {
        goodsList.push({
          goodsId: item.goodsId,
          goodsNum: item.goodsNum,
          skuId: item.skuId || '',
          goodsRefundMoney: item.goodsPayAmount,
          orderGoodsId: item.orderGoodsId || ''
        })
      })
      let params = {
        customerRemark: this.mark,
        orderId: this.orderId,
        afterSaleReasonId: this.afterSaleReasonId,
        refundVoucherList: this.imgFiles,
        goodsList: goodsList
      }
      doCancelPaidOrder(params).then(response => {
        if (response.isError) return
        this.$utils.showToast({ title: '已取消订单！', mask: true })
        this.timer = setTimeout(() => {
          this.$pt.navigateBack({delta: 1})
        }, 1500)
      })
    },
    cancelOrder() {
      if (!this.refundReason) return this.$utils.showToast({title: '请先选择退款原因!'})
      this.$pt.showModal({
        title: '温馨提示',
        content: '确认取消订单?',
        success: (res) => {
          if (res.confirm) {
            this.doSave()
          }
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.container{
  /deep/ .van-cell{
    &::after{
      border-bottom: unset;
    }
  }
  /deep/ .van-picker-column__item--selected{
    font-weight: bold;
  }
}
.img-box{
  border-radius: 5px;
  overflow: hidden;
  img{
    border-radius: 5px;
  }
}
.line-2{
  max-height: 34px;
  font-size: 13px;
}
.line-h-1{
  line-height: 1;
}
.color-red{
  color: #E60E0E;
}
.sku-block{
  margin-top: 7.5px;
  .sku-row{
    border-radius: 4px;
    background: #F8F8F8;
    .sku-detail{
      .line-1{
        line-height: unset;
      }
    }
  }
}
.upload-style{
  width: 80px;
  height: 80px;
  border: 1px dashed #A9A9A9;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  line-height: 1.2;
  color: #ABABAB;
}
.submit-btn{
  width: 294px;
  height: 44px;
  line-height: 44px;
  text-align: center;
  background: linear-gradient(to right, #FF9048, #FF4E23);
  border-radius: 22px;
  color: white;
  font-size: 16px;
  font-weight: bold;
  &::after{
    border: unset;
  }
}
.reason-cell{
  /deep/ .van-cell{
    padding: 10.5px 16px;
  }
}
</style>
